package admin

import (
	"errors"
	"exercise/application/yiran/app/libs"
	"exercise/application/yiran/app/model"
	"exercise/application/yiran/app/request/adminRequest"
	"fmt"
	"github.com/gin-gonic/gin"
)

type roomSeatService struct{}

func (*roomSeatService) List(ctx *gin.Context, request *adminRequest.RoomSeatListRequest) (map[string]interface{}, error) {
	schoolId, _ := ctx.Get("schoolId")
	list := make([]model.RoomSeatRJzwFloorRoom, 0)
	paging := model.Paging{}
	paging.Page = request.Page
	paging.PageSize = request.PageSize

	sql := "school_id = ?"
	where := []interface{}{schoolId}
	if request.JzwId > 0 {
		sql += " AND jzw_id = ? "
		where = append(where, request.JzwId)
	}

	if request.FloorId > 0 {
		sql += " AND floor_id = ? "
		where = append(where, request.FloorId)
	}

	if request.RoomId > 0 {
		sql += " AND room_id = ? "
		where = append(where, request.RoomId)
	}

	total, err := model.NewDb("").FindAllAndCount(&list, sql, where, model.OrderOrGroup{}, paging, []string{"Jzw", "Floor", "Room"})

	if err != nil {
		return nil, fmt.Errorf("暂无数据：%w", err)
	}

	return map[string]interface{}{
		"list":  list,
		"total": total,
	}, err
}

func (*roomSeatService) Add(ctx *gin.Context, request *adminRequest.AddRoomSeatRequest) (id int64, err error) {
	schoolId, _ := ctx.Get("schoolId")
	roomSeat := new(model.RoomSeat)
	roomSeat.JzwId = request.JzwId
	roomSeat.FloorId = request.FloorId
	roomSeat.RoomId = request.RoomId
	roomSeat.SeatNumber = request.SeatNumber
	roomSeat.SchoolId = schoolId.(int64)
	roomSeat.CreateTime = libs.CurrentTime()

	err = model.NewDb("").InsertRecord(roomSeat)
	if err != nil {
		return id, err
	}

	return roomSeat.Id, nil
}

func (*roomSeatService) Edit(request *adminRequest.EditRoomSeatRequest) error {
	roomSeat := new(model.RoomSeat)
	err := model.NewDb("").FindOne(roomSeat, "id = ? ", []interface{}{request.Id}, "*", []string{})
	if err != nil {
		return err
	}

	roomSeat.JzwId = request.JzwId
	roomSeat.FloorId = request.FloorId
	roomSeat.RoomId = request.RoomId
	roomSeat.SeatNumber = request.SeatNumber

	err = model.NewDb("").SaveRecord(roomSeat)
	if err != nil {
		return err
	}
	return nil
}

func (*roomSeatService) Detail(ctx *gin.Context) (res interface{}, err error) {
	id := ctx.Param("id")
	roomSeat := new(model.RoomSeat)
	err = model.NewDb("").FindOne(roomSeat, "id = ? ", []interface{}{id}, "*", []string{"Jzw", "Floor", "Room"})
	if err != nil {
		return nil, fmt.Errorf("数据异常：%w", err)
	}
	return roomSeat, err
}

func (*roomSeatService) Deleted(ctx *gin.Context) error {
	id := ctx.Param("id")
	roomSeat := new(model.RoomSeat)
	err := model.NewDb("").DeleteRecord(roomSeat, "id = ?", []interface{}{id})
	return err
}

func (*roomSeatService) InitRoom(ctx *gin.Context, request *adminRequest.InitRoomRequest) (err error) {
	schoolId, _ := ctx.Get("schoolId")
	for i := 1; i <= request.FloorNum; i++ {
		//新增楼层
		floor := new(model.Floor)
		floor.FloorName = libs.Int2String(i) + "层"
		floor.Floor = i
		floor.JzwId = request.JzwId
		floor.SchoolId = schoolId.(int64)
		err = model.NewDb("").InsertRecord(floor)
		if err != nil {
			return err
		}

		//创建每层的房间数
		for j := 1; j <= request.RoomNum; j++ {
			room := new(model.Room)
			//房间编号
			roomNum := fmt.Sprintf("%04d", i*1000+j)
			room.RoomName = roomNum + "室"
			room.FloorId = floor.Id
			room.JzwId = request.JzwId
			room.RoomNumber = roomNum
			room.SeatTotal = request.SeatTotal
			room.SchoolId = schoolId.(int64)
			err = model.NewDb("").InsertRecord(room)
			if err != nil {
				return err
			}
			//创建座位号
			for k := 1; k <= request.SeatTotal; k++ {
				roomSeat := new(model.RoomSeat)
				roomSeat.RoomId = room.Id
				roomSeat.SeatNumber = libs.Int2String(k)
				roomSeat.JzwId = request.JzwId
				roomSeat.FloorId = floor.Id
				roomSeat.SchoolId = schoolId.(int64)
				roomSeat.CreateTime = libs.CurrentTime()
				err = model.NewDb("").InsertRecord(roomSeat)
				if err != nil {
					return err
				}
			}
		}
	}
	return nil
}

func (*roomSeatService) ResetRoom(ctx *gin.Context, request *adminRequest.ResetRoomRequest) error {

	room := new(model.Room)
	err := model.NewDb("").FindOne(room, "id = ?", []interface{}{request.Id}, "*", []string{})
	if err != nil {
		return errors.New("房间不存在或已删除")
	}

	//清空房间所有的座位数
	query := model.NewDb("").Query()

	roomSeat := new(model.RoomSeat)
	err = query.Where("room_id = ?", request.Id).Delete(roomSeat).Error

	if err != nil {
		query.Rollback()
		return errors.New("清空房间异常")
	}

	//重新写入作为
	allData := make([]map[string]interface{}, 0)
	for i := 1; i <= request.SeatTotal; i++ {
		item := make(map[string]interface{}, 0)
		item["room_id"] = room.Id
		item["seat_number"] = i
		item["jzw_id"] = room.JzwId
		item["floor_id"] = room.FloorId
		item["school_id"] = room.SchoolId
		item["create_time"] = libs.CurrentTime()

		allData = append(allData, item)
		if len(allData) == 5 {
			err = query.Model(roomSeat).Create(allData).Error
			if err != nil {
				query.Rollback()
				return errors.New("重新分配座位失败")
			}
			allData = []map[string]interface{}{}
		}
	}

	if len(allData) > 0 {
		err = query.Model(roomSeat).Create(allData).Error
		if err != nil {
			query.Rollback()
			return fmt.Errorf("重新分配座位失败:%w ", err)
		}
	}

	err = query.Model(room).Where("id = ?", request.Id).Updates(map[string]interface{}{
		"seat_total": request.SeatTotal,
	}).Error

	if err != nil {
		query.Rollback()
		return errors.New("修改房间容量错误")
	}

	if err = query.Commit().Error; err != nil {
		query.Rollback()
		return err

	}

	return nil
}

func NewRoomSeatService() *roomSeatService {
	return &roomSeatService{}
}
